import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';


///[index]这个属性主要是为了给左边的时间轴画部件来用的
///[timeAxisSize]时间轴的大小必须要的。
///
/// 在[contentWidget]的左侧自动添加 竖向步骤条的组件
///
/// 支持[isDashLine]是否为虚线，在虚线的情况下，支持设置虚线每一段的间隔[dashSpace]和每个虚线段的长度[dashLength].
///
/// 线的顶端是图片，支持[iconWidget]配置。
///
/// 常用情况：
///    快递时间节点、跟进时间节点、日历时间节点等等
///
/// 如果不想显示分割线，那么可以将[lineColor] 设置为透明色
///
/// 该组件支持设置为灰色模式[isGrey]，在灰色模式下 线条颜色和icon颜色都是灰色
///
/// 布局步骤同[CustomPaint],因此[iconWidget]和[contentWidget]是顶部对齐的。
/// 如果想要设置icon的偏移，可以通过[iconTopPadding]设置
///
/// 最后一个的竖线不显示
///  ListView.builder(
///      shrinkWrap: true,
///      physics: NeverScrollableScrollPhysics(),
///      itemCount: 5,
///      itemBuilder: (context, index) {
///          if (index == 4) {
///             return KqStepLineWidget(
///                     lineWidth: 1,
///                     lineColor: Colors.transparent,
///                     contentWidget: Container(
///                       height: 50,
///                       color: getRandomColor(),
///                     ),
///                   );
///                 }
///          return KqStepLineWidget(
///                   lineWidth: 1,
///                   contentWidget: Container(
///                     height: 50,
///                     color: getRandomColor(),
///                ),
///          );
///   },
/// ),
///
/// 最后一个的竖线有颜色变化
///  ListView.builder(
///      shrinkWrap: true,
///      physics: NeverScrollableScrollPhysics(),
///      itemCount: 5,
///      itemBuilder: (context, index) {
///           if (index == 4) {
///              return KqStepLineWidget(
///                     lineWidth: 1,
///                     lineColor: <Color>[
///                       Color(0xFF0984F9),
///                       Colors.red,
///                     ],
///                     contentWidget: Container(
///                       height: 60,
///                       color: getRandomColor(),
///                     ),
///               );
///           }
///          return KqStepLineWidget(
///                   lineWidth: 1,
///                   contentWidget: Container(
///                     height: 50,
///                     color: getRandomColor(),
///                ),
///          );
///   },
/// ),
///
class KqStepLine extends StatefulWidget {
  ///整体是否是高亮，true 则使用highlightColor，否则使用normalColor
  final bool isHighlight;

  ///线的颜色
  final Color lineColor;

  /// 边框包裹的widget
  final Widget contentWidget;

  /// 线的宽度
  final double lineWidth;

  /// icon距离顶部的padding
  final double iconTopPadding;

  /// 是否画虚线
  final bool isDashLine;

  /// 是否圆点顶部的线
  final bool drawTopLine;

  /// 是否圆点底部的线
  final bool drawBottomLine;

  /// 每段虚线的长度
  final double dashLength;

  /// 每段虚线的间隔
  final double dashSpace;

  /// contentWidget距离左侧的padding
  final double contentLeftPadding;

  /// 普通状态(isHighlight=false)的颜色，默认值： Color(0xffeeeeee)
  final Color? normalColor;

  /// 高亮状态(isHighlight=true)的颜色，默认值，主题色
  final Color? highlightColor;

  /// 自定义icon的widget
  final Widget? iconWidget;

  const KqStepLine({
    Key? key,
    required this.contentWidget,
    this.isHighlight = false,
    this.lineColor = KqThemeColors.bgD,
    this.lineWidth = 1,
    this.iconTopPadding = 0,
    this.isDashLine = false,
    this.dashLength = 4,
    this.dashSpace = 4,
    this.drawTopLine = true,
    this.drawBottomLine = true,
    this.contentLeftPadding = 16,
    this.normalColor,
    this.highlightColor,
    this.iconWidget,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _KqStepLineState();
  }
}

class _KqStepLineState extends State<KqStepLine> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        CustomPaint(
          painter: _KqStepLinePainter(
              paintWidth: widget.lineWidth,
              iconTopPadding: widget.iconTopPadding,
              lineColor: widget.lineColor,
              isDash: widget.isDashLine,
              dashLength: widget.dashLength,
              dashSpace: widget.dashSpace,
              drawTopLine: widget.drawTopLine,
              drawBottomLine: widget.drawBottomLine),
          child: Container(
            padding: EdgeInsets.only(left: widget.contentLeftPadding),
            child: Container(
              child: widget.contentWidget,
            ),
          ),
        ),
        Container(
            padding: EdgeInsets.only(top: widget.iconTopPadding),
            child: widget.iconWidget ??
                (widget.isHighlight
                    ? _buildHighLightCircle()
                    : _buildGreyCircle())),
      ],
    );
  }

  Widget _buildGreyCircle() {
    return _buildColorCircleWidget(
        widget.normalColor ?? KqThemeColors.bgD, true);
  }

  Widget _buildHighLightCircle() {
    return _buildColorCircleWidget(
        widget.highlightColor ??
            KqThemeManager.instance.getConfig().commonConfig.mainLightColor ??
            KqThemeColors.textLightBlue,
        false);
  }

  Widget _buildColorCircleWidget(Color color, bool emptyHole) {
    return Container(
        height: 9.r,
        width: 9.r,
        decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: emptyHole ? Colors.transparent : color,
            border: Border.all(color: color, width: 1)),
        alignment: Alignment.center);
  }
}

class _KqStepLinePainter extends CustomPainter {
  /// 线的颜色
  final Color lineColor;

  /// 边框的宽度
  final double paintWidth;

  /// icon距离顶部的padding
  final double iconTopPadding;

  /// 是否绘制虚线
  final bool isDash;

  /// 虚线的间隔
  final double dashSpace;

  /// 虚线的长度
  final double dashLength;

  /// 绘制顶部线
  final bool drawTopLine;

  /// 绘制底部线
  final bool drawBottomLine;

  _KqStepLinePainter(
      {required this.lineColor,
      this.paintWidth = 1,
      required this.iconTopPadding,
      required this.isDash,
      required this.dashSpace,
      required this.dashLength,
      required this.drawTopLine,
      required this.drawBottomLine});

  final Paint _paint = Paint()
    ..strokeCap = StrokeCap.round // 画笔笔触类型
    ..isAntiAlias = true; // 是否启动抗锯齿;

  @override
  void paint(Canvas canvas, Size size) {
    _paint.style = PaintingStyle.stroke; // 画线模式
    _paint.strokeWidth = paintWidth;

    if (!isDash) {
      _drawFillLine(canvas, size);
    } else {
      _drawDashLine(canvas, size);
    }
  }

  void _drawDashLine(Canvas canvas, Size size) {
    var roundSize = 9.r;
    var roundSpace = 1.r;

    // 绘制圆圈顶部的线
    if (drawTopLine && iconTopPadding > 0) {
      double ori = 0;
      double temp = ori;
      //线条总长度 child的大小-上下的通栏-icon
      double height = iconTopPadding;
      //一共多少段
      int count = (height / (dashLength + dashSpace)).ceil();
      for (int i = 0, n = count; i < n; i++) {
        Path path = Path();
        path.moveTo(roundSize / 2, temp);
        if (temp + dashLength < size.height - roundSpace) {
          temp += dashLength;

          path.lineTo(roundSize / 2, temp);
          canvas.drawPath(path, _paint..color = lineColor);
          if (temp + dashSpace < size.height - roundSpace) {
            temp += dashSpace;
            path.lineTo(roundSize / 2, temp);
            canvas.drawPath(path, _paint..color = Colors.transparent);
          } else {
            path.lineTo(roundSize / 2, size.height - roundSpace);
            canvas.drawPath(path, _paint..color = Colors.transparent);
          }
        } else {
          path.lineTo(roundSize / 2, size.height - roundSpace);
          canvas.drawPath(path, _paint..color = lineColor);
        }
      }
    }

    // 绘制圆圈底部的线
    if (drawBottomLine) {
      double ori = roundSize + roundSpace + iconTopPadding;
      double temp = ori;
      //线条总长度 child的大小-上下的通栏-icon
      double height = size.height - ori - roundSpace;
      //一共多少段
      int count = (height / (dashLength + dashSpace)).ceil();
      for (int i = 0, n = count; i < n; i++) {
        Path path = Path();
        path.moveTo(roundSize / 2, temp);
        if (temp + dashLength < size.height - roundSpace) {
          temp += dashLength;

          path.lineTo(roundSize / 2, temp);
          canvas.drawPath(path, _paint..color = lineColor);
          if (temp + dashSpace < size.height - roundSpace) {
            temp += dashSpace;
            path.lineTo(roundSize / 2, temp);
            canvas.drawPath(path, _paint..color = Colors.transparent);
          } else {
            path.lineTo(roundSize / 2, size.height - roundSpace);
            canvas.drawPath(path, _paint..color = Colors.transparent);
          }
        } else {
          path.lineTo(roundSize / 2, size.height - roundSpace);
          canvas.drawPath(path, _paint..color = lineColor);
        }
      }
    }
  }

  void _drawFillLine(Canvas canvas, Size size) {

    var roundSize = 9.r;
    var x = roundSize / 2;

    if (drawTopLine) {
      double height = iconTopPadding;
      if (height <= 0) {
        return;
      }
      _paint.color = lineColor;
      Path path = Path();
      path.moveTo(x, 0);
      path.lineTo(x, height);
      canvas.drawPath(path, _paint);
    }

    if (drawBottomLine) {
      double height = size.height - 9.r - 1.r - iconTopPadding;
      if (height <= 0) {
        return;
      }
      double temp = 9.r + 1.r + iconTopPadding;
      _paint.color = lineColor;
      Path path = Path();
      path.moveTo(x, temp);
      path.lineTo(x, temp + height);
      canvas.drawPath(path, _paint);
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
